package com.coastwe.dahua.chapter03;

public class ArrayListDaHua {
    private int[] data;
    private int capacity;
    private int total;

    public ArrayListDaHua(int capacity) {
        this.data = new int[capacity];
        this.capacity = capacity;
        this.total = 0;
    }

    public int getElem(int index) {
        if (index >= total) {
            System.out.println("查找位置失败");
            return -1;
        }
        return data[index];
    }

    public boolean listInsert(int index, int value) {
        if (total == capacity) {
            System.out.println("位置已满");
            return false;
        }

        if (index > total) {
            System.out.println("插入位置有误");
            return false;
        }

        for (int i = total; i > index; i--) {
            data[i] = data[i - 1];
        }
        data[index] = value;
        total++;
        return true;
    }

    public boolean listDel(int index) {
        if (index >= total) {
            System.out.println("删除位置错误");
            return false;
        }

        for (int i = index + 1; i < total; i++) {
            data[i - 1] = data[i];
        }
        total--;
        return true;
    }

    public void printAll() {
        for (int i = 0; i < total; i++) {
            System.out.print(data[i] + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        ArrayListDaHua list = new ArrayListDaHua(5);
        list.listInsert(0, 1);
        list.listInsert(1, 2);
        list.listInsert(2, 3);
        list.listInsert(3, 4);
        list.printAll();
        list.listDel(3);
        list.printAll();
        System.out.println(list.getElem(6));
    }
}